package com.yonyou.jrmob.contacts.contact.activity;

/**
 * Created by 11985 on 2016/10/27.
 */
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.contact.adapter.SortAdapter_ct;
import com.yonyou.jrmob.contacts.contact.bean.ContactsVO_ct;
import com.yonyou.jrmob.contacts.contact.utils.CharacterParser_ct;
import com.yonyou.jrmob.contacts.contact.utils.PinyinComparator_ct;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bingoogolapple.titlebar.BGATitleBar;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;

public class MyDepartmentActivity_ct extends BaseActivityMob_lib {

    private ListView sortListView;
    private SortAdapter_ct adapter;

    private CharacterParser_ct characterParserCt;
    private List<ContactsVO_ct> contactsList;

    private PinyinComparator_ct pinyinComparatorCt;
    private String opFlag;//我的关注标识
    private String title;
    private Dialog loadingDialog;
    private BGATitleBar titleBar;
    private View statusBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        initActionbar();
//        SharedPreferences sharedPreferences = getSharedPreferences("saveData",
//                Activity.MODE_PRIVATE);

//        opFlag = sharedPreferences.getString("opFlag", "");
        opFlag = readLocationValue("opFlag");
        setContentView(R.layout.department_list_ct);
        StatusBarUtil.StatusBarLightMode(this);
        initView(); // 初始化控件
        initListener(); // 添加监听
        initData(); // 默认初始数据
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        loadingDialog = MobUtils.createLoadingDialog(this, "加载中请稍后...");
        characterParserCt = CharacterParser_ct.getInstance();
        pinyinComparatorCt = new PinyinComparator_ct();
        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        titleBar = (BGATitleBar) findViewById(R.id.my_department_title_bar);
//        statusBar = findViewById(R.id.my_department_status_bar);
        sortListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String name = adapter.getItem(position).getContactName();
                Intent intent = new Intent();
                intent.putExtra("name", name);
                intent.putExtra("cuserId", adapter.getItem(position).getCuserId());
                intent.setClass(MyDepartmentActivity_ct.this, ContactsDetailActivity_ct.class);
                startActivity(intent);
            }
        });
    }

    public void initListener() {
        titleBar.setDelegate(new BGATitleBar.Delegate() {
            @Override
            public void onClickLeftCtv() {
                finish();
            }

            @Override
            public void onClickTitleCtv() {

            }

            @Override
            public void onClickRightCtv() {

            }

            @Override
            public void onClickRightSecondaryCtv() {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
//        SharedPreferences mySharedPreferences = getSharedPreferences("saveData",
//                Activity.MODE_PRIVATE);
//        SharedPreferences.Editor editor = mySharedPreferences.edit();
//        editor.putString("opFlag", opFlag);
//        editor.commit();
        writeLocationFile("opFlag", opFlag);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /***
     * 调用后台服务
     */
    private void callService() {

        JSONObject json = new JSONObject();
        try {
            json.put("transtype", Constant.TRANSTYPE_DEPT);
            json.put("user_code", getUserInfoLRY().getUser_code());
            json.put("tenant_id", getUserInfoLRY().getTenant_id());
            json.put("uuidToken", Constant.TOKEN);
            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            if (null != loadingDialog && !loadingDialog.isShowing()) {
                loadingDialog.show();
            }
            MAServices_gkh.callMACommonService(MyDepartmentActivity_ct.this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json) {
                    LogUtils.e("我的部门："+json.toString());
                    JSONObject jsObject;
                    JSONArray jsArray;
                    try {
                        jsObject = (JSONObject) json.opt("result");
                        Object obj = jsObject.opt("retflag");
                        // 有错误的时候
                        if (null != obj && obj.toString().trim().equals("1")) {
                            String msg = jsObject.optString("msg").toString().trim();
                            if(!msg.isEmpty()||!msg.equals("0")){
                                showMessage(msg);
                            }
                            if(msg.contains("请重新登录")){
                                turnToLoginActivity(MyDepartmentActivity_ct.this);
                            }
                            return;
                        }
                        jsArray = (JSONArray) jsObject.get("contacalist");
                        contactsList = new ArrayList<ContactsVO_ct>();
                        for (int i = 0; i < jsArray.length(); i++) {
                            ContactsVO_ct contacts = new ContactsVO_ct();
                            contacts.setContactName(jsArray.getJSONObject(i).getString("user_name").trim());
                            contacts.setVdef(jsArray.getJSONObject(i).getString("user_mobilephone"));
                            contacts.setContactTel(jsArray.getJSONObject(i).getString("user_telephone"));
                            contacts.setUser_email(jsArray.getJSONObject(i).getString("user_email"));
                            contacts.setCuserId(jsArray.getJSONObject(i).getString("cuserid"));
                            contactsList.add(contacts);
                        }
                        contactsList = filledData(contactsList);
                        Collections.sort(contactsList, pinyinComparatorCt);
                        adapter = new SortAdapter_ct(MyDepartmentActivity_ct.this, contactsList, true);
                        sortListView.setAdapter(adapter);
                        if (loadingDialog != null && loadingDialog.isShowing()) {
                            loadingDialog.dismiss();
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                }

                @Override
                public void error(String arg0, String arg1) {
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();
                    }

                    if (!arg1.equals("")){
                        // 设置登录按钮可用性(登录请求后台有反应后可用)
                        Toast.makeText(MyDepartmentActivity_ct.this, arg0 + arg1,
                                Toast.LENGTH_LONG).show();
                    }

                    adapter = new SortAdapter_ct(MyDepartmentActivity_ct.this, new ArrayList<ContactsVO_ct>(), true);
                    sortListView.setAdapter(adapter);
                }
            }, json);

        } catch (Exception e) {
            // 设置登录按钮可用性(登录请求后台有反应后可用)
            Log.e("mmmm", e + "");
            e.printStackTrace();
        }
    }

    /**
     * 数据初始化
     */
    @Override
    public void initData() {
        opFlag = getIntent().getExtras().getString("opflag");
        title = getIntent().getExtras().getString("title");
        titleBar.setTitleText(title);
        callService();
    }

    /**
     * 姓名首字母转换
     */
    private List<ContactsVO_ct> filledData(List<ContactsVO_ct> contactsList) {
        if (contactsList == null) {
            contactsList = new ArrayList<ContactsVO_ct>();
        }
        for (int i = 0; i < contactsList.size(); i++) {
            String pinyin = characterParserCt.getSelling(contactsList.get(i).getContactName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                contactsList.get(i).setSortLetters(sortString.toUpperCase());
            } else {
                contactsList.get(i).setSortLetters("#");
            }
        }
        return contactsList;

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (opFlag.equals("0")) {
            initData();
        }
    }

}

